package com.flashcash.solu.common.update;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Process;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.flashcash.solu.BuildConfig;
import com.flashcash.solu.R;
import com.flashcash.solu.bean.VersionBean;
import com.flashcash.solu.common.EventCollection;
import com.flashcash.solu.widget.xleotoast.XLeoToast;
import com.x.leo.apphelper.log.XLog;

import java.util.List;

/**
 * @作者:My
 * @创建日期: 2017/4/26 16:24
 * @描述:${TODO}
 * @更新者:${Author}$
 * @更新时间:${Date}$
 * @更新描述:${TODO}
 */

public class UpdateManager {
    private Integer mVersoionCode;
    private VersionBean mVersonBean;
    private Context mContext;

    public UpdateManager(Context context, VersionBean versonBean) {
        mContext = context;
        mVersonBean = versonBean;
    }

    public UpdateManager(Context context, Integer versonBean) {
        mContext = context;
        mVersoionCode = versonBean;
    }

    public UpdateManager(Context context, EventCollection.NeedUpdateEvent event) {
        mContext = context;
        if (event != null) {
            mVersonBean = new VersionBean();
            mVersonBean.setLatestVersion(event.getLatestVersion());
            mVersonBean.setLatestVersionCode(event.getLatestVersionCode());
            mVersonBean.setReleaseNotes(event.getReleaseNotes());
        }
    }

    public void start() {
        createUpdateDialog();
    }

    private void createUpdateDialog() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_update, null);
        Dialog downloadDialog = new AlertDialog.Builder(mContext)
                .setView(view)
                .setCancelable(false)
                .create();
        view.findViewById(R.id.btn_dialog_update_download).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(BuildConfig.APP_URL)) {
                    gotoDownLoadApk(v);
                }

                doDeleayQuest();
            }
        });
        try {
            if (mVersonBean != null && mVersonBean.getReleaseNotes() != null && mVersonBean.getReleaseNotes().size() > 0) {
                StringBuilder sb = new StringBuilder();
                for (String s : mVersonBean.getReleaseNotes()) {
                    sb.append(s + "\n");
                }
                sb.deleteCharAt(sb.length() - 1);
                ((TextView) view.findViewById(R.id.tv_update_notes)).setText(sb.toString());
            } else {

            }
        } catch (Exception e) {
            XLog.INSTANCE.e("append String error:" + e.getMessage(), e, 100);
        }
        downloadDialog.setCanceledOnTouchOutside(false);
        downloadDialog.setCancelable(false);
        downloadDialog.show();
    }

    private void gotoDownLoadApk(View v) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(BuildConfig.APP_URL));
            List<ResolveInfo> resolveInfos = v.getContext().getPackageManager().queryIntentActivities(intent, 0);
            if (resolveInfos == null || resolveInfos.size() <= 0) {
                XLeoToast.showMessage(R.string.show_download_on_google_player);
            }else{
                for (ResolveInfo resolveInfo : resolveInfos) {
                    if (resolveInfo.activityInfo.packageName.toLowerCase().contains("com.android.vending")
                            || resolveInfo.activityInfo.name.toLowerCase().contains("com.android.vending")
                            || resolveInfo.activityInfo.processName.toLowerCase().contains("com.android.vending")) {
                        intent.setPackage(resolveInfo.activityInfo.packageName);
                        break;
                    }
                }
            }
            v.getContext().startActivity(intent);
        } catch (Exception e) {
            XLeoToast.showMessage(R.string.show_download_on_google_player);
        }
    }

    private void doDeleayQuest() {
        Process.killProcess(Process.myPid());
        System.exit(0);
    }

//    private void initDownloadView(View view, final Dialog downloadDialog, final VersionBean versionBean) {
//        ImageView title = (ImageView) view.findViewById(R.id.tv_dialog_update_title);
//        TextView message = (TextView) view.findViewById(R.id.tv_dialog_update_message);
//        final LinearLayout linearlayout = (LinearLayout) view.findViewById(R.id.ll_dialog_update_message);
//        final ProgressBar pb = (ProgressBar) view.findViewById(R.id.pb_dialog_update);
//        StringBuffer s = new StringBuffer();
//        for (String s1 : versionBean.getReleaseNotes()) {
//            s.append(s1 + "\n");
//        }
//        message.setText(s);
//        view.findViewById(R.id.btn_dialog_update_download).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                pb.setVisibility(View.VISIBLE);
//                linearlayout.setVisibility(View.GONE);
//                downloadAndInstall(versionBean, downloadDialog, pb);
//            }
//        });
//    }
//
//
//    private void downloadAndInstall(final VersionBean versionBean, final Dialog downloadDialog, final ProgressBar pb) {
//        Observable.create(new Observable.OnSubscribe<File>() {
//
//            @Override
//            public void call(final Subscriber<? super File> subscriber) {
//                new DownloadManager(mContext, versionBean.getUrl(), new DownloadManager.OnDownloadListener() {
//                    @Override
//                    public void onProgress(int progress) {
//                        if (pb != null) {
//                            pb.setProgress(progress);
//                        }
//                    }
//
//                    @Override
//                    public void onComplete(File file) {
//                        downloadDialog.dismiss();
//                        subscriber.onNext(file);
//                    }
//
//                    @Override
//                    public void onError(Throwable t) {
//                        subscriber.onError(t);
//                    }
//                }).startDownLoad();
//            }
//        }).subscribeOn(Schedulers.newThread())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Subscriber<File>() {
//                    @Override
//                    public void onCompleted() {
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        XLog.INSTANCE.e("",e,100);
//                        XLeoToast.showMessage(mContext.getString(R.string.show_update_on_error) + e.getMessage());
//                        android.os.Process.killProcess(android.os.Process.myPid());
//                        downloadDialog.dismiss();
//                    }
//
//                    @Override
//                    public void onNext(File file) {
//                        //                        if (versionBean.getApkSize() != file.length()) {
//                        //                            XLeoToast.showMessage(R.string.show_download_on_google_player);
//                        //                        }else {
//                        Intent installIntent = new Intent();
//                        installIntent.setAction(Intent.ACTION_VIEW);
//                        installIntent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
//                        installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        mContext.startActivity(installIntent);
//                    }
//                    //                    }
//                });
//    }

}
